<template>
  <div class="data-model">
    <!-- 顶部工具栏 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <h2>数据模型</h2>
        <span class="subtitle">管理数据源、表关系和计算字段</span>
      </div>
      <div class="toolbar-right">
        <el-button type="primary" @click="showDataSourceDialog = true">
          <el-icon><Plus /></el-icon>
          添加数据源
        </el-button>
        <el-button @click="showRelationshipDialog = true">
          <el-icon><Connection /></el-icon>
          管理关系
        </el-button>
        <el-button @click="showCalculatedFieldDialog = true">
          <el-icon><Operation /></el-icon>
          计算字段
        </el-button>
        <el-button @click="refreshModel">
          <el-icon><Refresh /></el-icon>
          刷新模型
        </el-button>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 左侧数据源面板 -->
      <div class="left-panel">
        <div class="panel-header">
          <h4>数据源</h4>
          <el-button size="small" text @click="showDataSourceDialog = true">
            <el-icon><Plus /></el-icon>
          </el-button>
        </div>
        
        <div class="data-sources">
          <div 
            v-for="dataSource in dataSources" 
            :key="dataSource.id"
            class="data-source-item"
            :class="{ 'active': selectedDataSource?.id === dataSource.id }"
            @click="selectDataSource(dataSource)">
            
            <div class="data-source-header">
              <el-icon class="data-source-icon">
                <component :is="getDataSourceIcon(dataSource.type)" />
              </el-icon>
              <span class="data-source-name">{{ dataSource.name }}</span>
              <el-dropdown trigger="click" @command="handleDataSourceAction">
                <el-button size="small" text>
                  <el-icon><MoreFilled /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item :command="`edit_${dataSource.id}`">编辑</el-dropdown-item>
                    <el-dropdown-item :command="`refresh_${dataSource.id}`">刷新</el-dropdown-item>
                    <el-dropdown-item :command="`delete_${dataSource.id}`" divided>删除</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
            
            <div class="data-source-info">
              <span class="data-source-type">{{ getDataSourceTypeLabel(dataSource.type) }}</span>
              <span class="data-source-status" :class="dataSource.status">
                {{ getStatusLabel(dataSource.status) }}
              </span>
            </div>
            
            <!-- 表列表 -->
            <div v-if="dataSource.tables" class="tables-list">
              <div 
                v-for="table in dataSource.tables" 
                :key="table.id"
                class="table-item"
                :class="{ 'selected': selectedTable?.id === table.id }"
                @click.stop="selectTable(table)">
                
                <el-icon><Grid /></el-icon>
                <span class="table-name">{{ table.name }}</span>
                <span class="table-rows">({{ table.rowCount || 0 }} 行)</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 中间模型设计区域 -->
      <div class="model-canvas">
        <div class="canvas-header">
          <h4>模型关系图</h4>
          <div class="canvas-tools">
            <el-button-group size="small">
              <el-button @click="zoomIn">
                <el-icon><ZoomIn /></el-icon>
              </el-button>
              <el-button @click="resetZoom">100%</el-button>
              <el-button @click="zoomOut">
                <el-icon><ZoomOut /></el-icon>
              </el-button>
            </el-button-group>
            <el-button size="small" @click="autoLayout">
              <el-icon><Rank /></el-icon>
              自动布局
            </el-button>
          </div>
        </div>
        
        <div 
          ref="canvasContainer" 
          class="canvas-container"
          :style="{ transform: `scale(${zoomLevel})` }">
          
          <!-- SVG关系线 -->
          <svg class="relationships-svg" :width="canvasSize.width" :height="canvasSize.height">
            <defs>
              <marker id="arrowhead" markerWidth="10" markerHeight="7" 
                      refX="9" refY="3.5" orient="auto">
                <polygon points="0 0, 10 3.5, 0 7" fill="#409EFF" />
              </marker>
            </defs>
            
            <g v-for="relationship in relationships" :key="relationship.id">
              <path 
                :d="getRelationshipPath(relationship)"
                stroke="#409EFF"
                stroke-width="2"
                fill="none"
                marker-end="url(#arrowhead)"
                :class="{ 'active': selectedRelationship?.id === relationship.id }"
                @click="selectRelationship(relationship)" />
              
              <!-- 关系标签 -->
              <text 
                :x="getRelationshipLabelPosition(relationship).x"
                :y="getRelationshipLabelPosition(relationship).y"
                text-anchor="middle"
                class="relationship-label">
                {{ getRelationshipLabel(relationship) }}
              </text>
            </g>
          </svg>
          
          <!-- 表组件 -->
          <div 
            v-for="table in modelTables" 
            :key="table.id"
            class="table-component"
            :style="getTableStyle(table)"
            :class="{ 'selected': selectedTable?.id === table.id }"
            @click="selectTable(table)"
            @mousedown="startDragTable(table, $event)">
            
            <div class="table-header">
              <el-icon><Grid /></el-icon>
              <span class="table-title">{{ table.name }}</span>
              <el-dropdown trigger="click" @command="handleTableAction">
                <el-button size="small" text>
                  <el-icon><MoreFilled /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item :command="`preview_${table.id}`">预览数据</el-dropdown-item>
                    <el-dropdown-item :command="`edit_${table.id}`">编辑表</el-dropdown-item>
                    <el-dropdown-item :command="`relationship_${table.id}`">创建关系</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
            
            <div class="table-fields">
              <div 
                v-for="field in table.fields" 
                :key="field.id"
                class="field-item"
                :class="{ 
                  'primary-key': field.isPrimaryKey,
                  'foreign-key': field.isForeignKey,
                  'calculated': field.isCalculated
                }"
                @click.stop="selectField(field)">
                
                <el-icon class="field-icon">
                  <component :is="getFieldIcon(field)" />
                </el-icon>
                <span class="field-name">{{ field.name }}</span>
                <span class="field-type">{{ field.dataType }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧属性面板 -->
      <div class="right-panel">
        <div class="panel-header">
          <h4>属性</h4>
        </div>
        
        <div class="properties-content">
          <!-- 表属性 -->
          <div v-if="selectedTable" class="property-section">
            <h5>表属性</h5>
            <el-form label-position="top" size="small">
              <el-form-item label="表名">
                <el-input v-model="selectedTable.name" />
              </el-form-item>
              <el-form-item label="描述">
                <el-input v-model="selectedTable.description" type="textarea" :rows="3" />
              </el-form-item>
              <el-form-item label="数据行数">
                <el-input v-model="selectedTable.rowCount" disabled />
              </el-form-item>
            </el-form>
          </div>
          
          <!-- 字段属性 -->
          <div v-if="selectedField" class="property-section">
            <h5>字段属性</h5>
            <el-form label-position="top" size="small">
              <el-form-item label="字段名">
                <el-input v-model="selectedField.name" />
              </el-form-item>
              <el-form-item label="数据类型">
                <el-select v-model="selectedField.dataType" style="width: 100%">
                  <el-option label="文本" value="text" />
                  <el-option label="数字" value="number" />
                  <el-option label="日期" value="date" />
                  <el-option label="布尔" value="boolean" />
                  <el-option label="货币" value="currency" />
                </el-select>
              </el-form-item>
              <el-form-item label="字段类型">
                <el-select v-model="selectedField.category" style="width: 100%">
                  <el-option label="维度" value="维度" />
                  <el-option label="度量值" value="度量值" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-checkbox v-model="selectedField.isPrimaryKey">主键</el-checkbox>
              </el-form-item>
              <el-form-item>
                <el-checkbox v-model="selectedField.isForeignKey">外键</el-checkbox>
              </el-form-item>
              <el-form-item>
                <el-checkbox v-model="selectedField.isCalculated">计算字段</el-checkbox>
              </el-form-item>
            </el-form>
          </div>
          
          <!-- 关系属性 -->
          <div v-if="selectedRelationship" class="property-section">
            <h5>关系属性</h5>
            <el-form label-position="top" size="small">
              <el-form-item label="关系类型">
                <el-select v-model="selectedRelationship.type" style="width: 100%">
                  <el-option label="一对一" value="one-to-one" />
                  <el-option label="一对多" value="one-to-many" />
                  <el-option label="多对多" value="many-to-many" />
                </el-select>
              </el-form-item>
              <el-form-item label="交叉筛选方向">
                <el-select v-model="selectedRelationship.crossFilterDirection" style="width: 100%">
                  <el-option label="单向" value="single" />
                  <el-option label="双向" value="both" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-checkbox v-model="selectedRelationship.isActive">激活关系</el-checkbox>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
    </div>

    <!-- 数据源对话框 -->
    <DataSourceDialog v-model="showDataSourceDialog" @data-source-added="handleDataSourceAdded" />
    
    <!-- 关系管理对话框 -->
    <RelationshipDialog v-model="showRelationshipDialog" :tables="modelTables" @relationship-created="handleRelationshipCreated" />
    
    <!-- 计算字段对话框 -->
    <CalculatedFieldDialog v-model="showCalculatedFieldDialog" :tables="modelTables" @field-created="handleCalculatedFieldCreated" />
    
    <!-- 数据预览对话框 -->
    <DataPreviewDialog v-model="showDataPreviewDialog" :table="previewTable" />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { useDataModelStore } from '../stores/dataModelStore'
import DataSourceDialog from '../components/DataModel/DataSourceDialog.vue'
import RelationshipDialog from '../components/DataModel/RelationshipDialog.vue'
import CalculatedFieldDialog from '../components/DataModel/CalculatedFieldDialog.vue'
import DataPreviewDialog from '../components/DataModel/DataPreviewDialog.vue'
import { 
  Plus, 
  Connection, 
  Operation, 
  Refresh, 
  MoreFilled, 
  Grid, 
  ZoomIn, 
  ZoomOut, 
  Rank,
  Document,
  Coin,
  Calendar,
  Key,
  Link
} from '@element-plus/icons-vue'

// 使用数据模型store
const dataModelStore = useDataModelStore()

// 响应式数据
const showDataSourceDialog = ref(false)
const showRelationshipDialog = ref(false)
const showCalculatedFieldDialog = ref(false)
const showDataPreviewDialog = ref(false)
const selectedDataSource = ref(null)
const selectedTable = ref(null)
const selectedField = ref(null)
const selectedRelationship = ref(null)
const previewTable = ref(null)
const canvasContainer = ref(null)
const zoomLevel = ref(1)
const canvasSize = ref({ width: 1200, height: 800 })

// 计算属性
const dataSources = computed(() => dataModelStore.dataSources)
const modelTables = computed(() => dataModelStore.modelTables)
const relationships = computed(() => dataModelStore.relationships)

// 方法
const selectDataSource = (dataSource) => {
  selectedDataSource.value = dataSource
  selectedTable.value = null
  selectedField.value = null
  selectedRelationship.value = null
}

const selectTable = (table) => {
  selectedTable.value = table
  selectedField.value = null
  selectedRelationship.value = null
}

const selectField = (field) => {
  selectedField.value = field
  selectedRelationship.value = null
}

const selectRelationship = (relationship) => {
  selectedRelationship.value = relationship
  selectedTable.value = null
  selectedField.value = null
}

const getDataSourceIcon = (type) => {
  const icons = {
    'json': Document,
    'csv': Document,
    'excel': Document,
    'database': Grid,
    'api': Connection
  }
  return icons[type] || Document
}

const getDataSourceTypeLabel = (type) => {
  const labels = {
    'json': 'JSON文件',
    'csv': 'CSV文件',
    'excel': 'Excel文件',
    'database': '数据库',
    'api': 'API接口'
  }
  return labels[type] || type
}

const getStatusLabel = (status) => {
  const labels = {
    'connected': '已连接',
    'disconnected': '未连接',
    'error': '错误'
  }
  return labels[status] || status
}

const getFieldIcon = (field) => {
  if (field.isPrimaryKey) return Key
  if (field.isForeignKey) return Link
  if (field.dataType === 'number' || field.dataType === 'currency') return Coin
  if (field.dataType === 'date') return Calendar
  return Document
}

const getTableStyle = (table) => {
  return {
    position: 'absolute',
    left: `${table.position?.x || 100}px`,
    top: `${table.position?.y || 100}px`,
    transform: `scale(${zoomLevel.value})`
  }
}

const getRelationshipPath = (relationship) => {
  // 简化的路径计算，实际应该根据表的位置计算
  const fromTable = modelTables.value.find(t => t.id === relationship.fromTable)
  const toTable = modelTables.value.find(t => t.id === relationship.toTable)
  
  if (!fromTable || !toTable) return ''
  
  const fromX = (fromTable.position?.x || 100) + 150
  const fromY = (fromTable.position?.y || 100) + 50
  const toX = (toTable.position?.x || 300) + 150
  const toY = (toTable.position?.y || 300) + 50
  
  return `M ${fromX} ${fromY} L ${toX} ${toY}`
}

const getRelationshipLabelPosition = (relationship) => {
  const fromTable = modelTables.value.find(t => t.id === relationship.fromTable)
  const toTable = modelTables.value.find(t => t.id === relationship.toTable)
  
  if (!fromTable || !toTable) return { x: 0, y: 0 }
  
  const fromX = (fromTable.position?.x || 100) + 150
  const fromY = (fromTable.position?.y || 100) + 50
  const toX = (toTable.position?.x || 300) + 150
  const toY = (toTable.position?.y || 300) + 50
  
  return {
    x: (fromX + toX) / 2,
    y: (fromY + toY) / 2 - 10
  }
}

const getRelationshipLabel = (relationship) => {
  const labels = {
    'one-to-one': '1:1',
    'one-to-many': '1:N',
    'many-to-many': 'N:N'
  }
  return labels[relationship.type] || relationship.type
}

const startDragTable = (table, event) => {
  // 实现表的拖拽功能
  console.log('开始拖拽表:', table.name)
}

const zoomIn = () => {
  zoomLevel.value = Math.min(zoomLevel.value + 0.1, 2)
}

const zoomOut = () => {
  zoomLevel.value = Math.max(zoomLevel.value - 0.1, 0.5)
}

const resetZoom = () => {
  zoomLevel.value = 1
}

const autoLayout = () => {
  // 实现自动布局算法
  console.log('自动布局')
}

const refreshModel = () => {
  dataModelStore.refreshModel()
}

const handleDataSourceAction = (command) => {
  const [action, id] = command.split('_')
  console.log('数据源操作:', action, id)
}

const handleTableAction = (command) => {
  const [action, id] = command.split('_')
  if (action === 'preview') {
    const table = modelTables.value.find(t => t.id === id)
    previewTable.value = table
    showDataPreviewDialog.value = true
  }
  console.log('表操作:', action, id)
}

const handleDataSourceAdded = (dataSource) => {
  dataModelStore.addDataSource(dataSource)
}

const handleRelationshipCreated = (relationship) => {
  dataModelStore.addRelationship(relationship)
}

const handleCalculatedFieldCreated = (field) => {
  dataModelStore.addCalculatedField(field)
}

onMounted(() => {
  // 初始化画布尺寸
  nextTick(() => {
    if (canvasContainer.value) {
      const rect = canvasContainer.value.getBoundingClientRect()
      canvasSize.value = { width: rect.width, height: rect.height }
    }
  })
})
</script>

<style scoped>
.data-model {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f7fa;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 24px;
  background: white;
  border-bottom: 1px solid #e4e7ed;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.toolbar-left h2 {
  margin: 0 0 4px 0;
  color: #303133;
  font-size: 18px;
}

.subtitle {
  color: #909399;
  font-size: 12px;
}

.toolbar-right {
  display: flex;
  gap: 12px;
}

.main-content {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.left-panel {
  width: 280px;
  background: white;
  border-right: 1px solid #e4e7ed;
  display: flex;
  flex-direction: column;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #e4e7ed;
}

.panel-header h4 {
  margin: 0;
  color: #303133;
  font-size: 16px;
}

.data-sources {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
}

.data-source-item {
  margin-bottom: 8px;
  padding: 12px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.data-source-item:hover {
  border-color: #409EFF;
  background: #ecf5ff;
}

.data-source-item.active {
  border-color: #409EFF;
  background: #ecf5ff;
}

.data-source-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.data-source-icon {
  color: #409EFF;
}

.data-source-name {
  flex: 1;
  font-weight: 600;
  color: #303133;
}

.data-source-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #909399;
  margin-bottom: 8px;
}

.data-source-status.connected {
  color: #67C23A;
}

.data-source-status.error {
  color: #F56C6C;
}

.tables-list {
  border-top: 1px solid #f0f0f0;
  padding-top: 8px;
}

.table-item {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 6px 8px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  transition: background 0.2s ease;
}

.table-item:hover {
  background: rgba(64, 158, 255, 0.1);
}

.table-item.selected {
  background: rgba(64, 158, 255, 0.2);
  color: #409EFF;
}

.table-name {
  flex: 1;
  font-weight: 500;
}

.table-rows {
  color: #909399;
}

.model-canvas {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: white;
}

.canvas-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #e4e7ed;
}

.canvas-header h4 {
  margin: 0;
  color: #303133;
  font-size: 16px;
}

.canvas-tools {
  display: flex;
  gap: 12px;
  align-items: center;
}

.canvas-container {
  flex: 1;
  position: relative;
  overflow: auto;
  background: #fafafa;
  background-image: 
    linear-gradient(rgba(0,0,0,.1) 1px, transparent 1px),
    linear-gradient(90deg, rgba(0,0,0,.1) 1px, transparent 1px);
  background-size: 20px 20px;
}

.relationships-svg {
  position: absolute;
  top: 0;
  left: 0;
  pointer-events: none;
  z-index: 1;
}

.relationships-svg path {
  pointer-events: stroke;
  cursor: pointer;
}

.relationships-svg path.active {
  stroke: #E6A23C;
  stroke-width: 3;
}

.relationship-label {
  font-size: 12px;
  fill: #409EFF;
  font-weight: 600;
}

.table-component {
  width: 300px;
  background: white;
  border: 2px solid #e4e7ed;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  cursor: move;
  z-index: 2;
}

.table-component.selected {
  border-color: #409EFF;
  box-shadow: 0 4px 16px rgba(64, 158, 255, 0.3);
}

.table-header {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px;
  background: #f8f9fa;
  border-bottom: 1px solid #e4e7ed;
  border-radius: 6px 6px 0 0;
}

.table-title {
  flex: 1;
  font-weight: 600;
  color: #303133;
}

.table-fields {
  max-height: 300px;
  overflow-y: auto;
}

.field-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background 0.2s ease;
}

.field-item:hover {
  background: #f8f9fa;
}

.field-item:last-child {
  border-bottom: none;
}

.field-item.primary-key {
  background: rgba(255, 193, 7, 0.1);
}

.field-item.foreign-key {
  background: rgba(64, 158, 255, 0.1);
}

.field-item.calculated {
  background: rgba(103, 194, 58, 0.1);
}

.field-icon {
  color: #909399;
}

.field-item.primary-key .field-icon {
  color: #E6A23C;
}

.field-item.foreign-key .field-icon {
  color: #409EFF;
}

.field-item.calculated .field-icon {
  color: #67C23A;
}

.field-name {
  flex: 1;
  font-weight: 500;
  color: #303133;
}

.field-type {
  font-size: 12px;
  color: #909399;
}

.right-panel {
  width: 320px;
  background: white;
  border-left: 1px solid #e4e7ed;
  display: flex;
  flex-direction: column;
}

.properties-content {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
}

.property-section {
  margin-bottom: 24px;
}

.property-section h5 {
  margin: 0 0 16px 0;
  color: #303133;
  font-size: 14px;
  font-weight: 600;
}
</style>
